<?php
/**
 * 用户控制器
 */

declare (strict_types = 1);

namespace app\controller\user;

use app\BaseController;
use app\model\admin\User as UserModel;
use app\model\admin\Department;
use app\model\admin\Position;
use think\facade\Request;

class User extends BaseController
{
    /**
     * 用户模型实例
     * @var UserModel
     */
    protected $userModel;

    /**
     * 部门模型实例
     * @var Department
     */
    protected $departmentModel;

    /**
     * 职位模型实例
     * @var Position
     */
    protected $positionModel;

    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->userModel = new UserModel();
        $this->departmentModel = new Department();
        $this->positionModel = new Position();
    }

    /**
     * 获取用户列表
     */
    public function index()
    {
        try {
            $params = Request::param();
            $page = isset($params['page']) ? (int)$params['page'] : 1;
            $limit = isset($params['limit']) ? (int)$params['limit'] : 15;
            
            $result = $this->userModel->getList($params, $page, $limit);
            // 获取用户列表
            $list = $result['list'];

            // 预加载部门信息（避免N+1查询）
            if (!$list->isEmpty()) {
                $departmentIds = array_filter(array_unique(array_column($list->toArray(), 'did')));
                if (!empty($departmentIds)) {
                    $departments = $this->departmentModel
                        ->where('id', 'in', $departmentIds)
                        ->where('status', '>', 0)
                        ->column('title', 'id');
                }

                // 预加载职位信息（避免N+1查询）
                $positionIds = array_filter(array_unique(array_column($list->toArray(), 'position_id')));
                if (!empty($positionIds)) {
                    $positions = $this->positionModel
                        ->where('id', 'in', $positionIds)
                        ->column('title', 'id');
                }

                // 处理数据
                foreach ($list as &$user) {
                    $user['dept_name'] = $departments[$user['did']] ?? '';
                    $user['position_name'] = $positions[$user['position_id']] ?? '';
                    $user['department'] = $user['dept_name'];
                    $user['position'] = $user['position_name'];
                }
                unset($user);
            }

            return $this->paginate($list->toArray(), $result['total'], $page, $limit);
        } catch (\Exception $e) {
            return $this->error('获取用户列表失败: '.$e->getMessage());
        }
    }
    
    /**
     * 搜索用户
     */
    public function search()
    {
        $keyword = Request::param('keyword', '');
        
        if (empty($keyword)) {
            return $this->success([], 'success');
        }
        
        try {
            // 查询启用的用户列表，支持关键词搜索
            $list = $this->userModel
                ->where('status', 1)
                ->where('name', 'like', '%' . trim($keyword) . '%')
                ->order('id', 'asc')
                ->limit(20) // 限制返回数量，避免数据量过大
                ->select()
                ->toArray();
            
            return $this->success($list, 'success');
        } catch (\Exception $e) {
            return $this->error('搜索失败', 500);
        }
    }
    
    /**
     * 查看用户详情
     */
    public function view()
    {
        $param = Request::param();
        
        if (empty($param['id'])) {
            return $this->error('参数错误', 400);
        }
        
        try {
            $user = $this->userModel->getInfoById($param['id']);
            
            if (empty($user)) {
                return $this->error('用户不存在', 404);
            }

            // 获取部门信息（使用更高效的查询）
            $did = $user->getAttr('did');
            if ($did > 0) {
                $department = $this->departmentModel
                    ->where('id', $did)
                    ->where('status', '>', 0)
                    ->cache(60)  // 缓存60秒
                    ->value('title');
                $user->department = $department ?: '';
            } else {
                $user->department = '';
            }
            
            // 将模型对象转换为数组
            $userData = $user->toArray();
            
            return $this->success($userData, 'success');
        } catch (\Exception $e) {
            return $this->error('获取失败', 500);
        }
    }
    
    /**
     * 新增用户
     */
    public function add()
    {
        $param = Request::param();
        
        // 数据验证
        if (empty($param['name'])) {
            return $this->error('用户名称不能为空', 400);
        }
        
        try {
            // 检查用户名是否已存在
            if (!empty($param['username']) && $this->userModel->checkUsernameExists($param['username'])) {
                return $this->error('用户名已存在', 400);
            }
            
            // 生成初始密码
            $initialPassword = generate_initial_password(6);
            
            // 准备用户数据
            $data = [
                'name' => $param['name'],
                'username' => $param['username'] ?? '',
                'reg_pwd' => $initialPassword,  // 修改这里：使用reg_pwd字段而不是pwd字段
                'did' => $param['did'] ?? 0,
                'position_id' => $param['position_id'] ?? 0,
                'mobile' => $param['mobile'] ?? '',
                'email' => $param['email'] ?? '',
                'sex' => $param['sex'] ?? 1,
                'status' => $param['status'] ?? 1,
                'entry_time' => isset($param['entry_time']) ? strtotime($param['entry_time']) : 0,
            ];
            
            // 新增用户
            $userId = $this->userModel->createUserInfo($data);
            
            if ($userId) {
                return $this->success(['id' => $userId], '保存成功');
            } else {
                return $this->error('保存失败', 500);
            }
        } catch (\Exception $e) {
            return $this->error('保存失败: ' . $e->getMessage(), 500);
        }
    }
    
    /**
     * 编辑用户
     */
    public function edit()
    {
        $param = Request::param();
        
        // 数据验证
        if (empty($param['id'])) {
            return $this->error('参数错误', 400);
        }
        
        if (empty($param['name'])) {
            return $this->error('用户名称不能为空', 400);
        }
        
        try {
            // 检查用户是否存在
            $user = $this->userModel->getInfoById($param['id']);
            
            if (!$user) {
                return $this->error('用户不存在', 404);
            }
            
            // 检查用户名是否已存在（排除当前用户）
            if (!empty($param['username']) && $this->userModel->checkUsernameExists($param['username'], $param['id'])) {
                return $this->error('用户名已存在', 400);
            }
            
            // 准备更新数据
            $data = [
                'name' => $param['name'],
                'username' => $param['username'] ?? $user->getAttr('username'),
                'did' => $param['did'] ?? $user->getAttr('did'),
                'position_id' => $param['position_id'] ?? $user->getAttr('position_id'),
                'mobile' => $param['mobile'] ?? $user->getAttr('mobile'),
                'email' => $param['email'] ?? $user->getAttr('email'),
                'sex' => $param['sex'] ?? $user->getAttr('sex'),
                'status' => $param['status'] ?? $user->getAttr('status'),
                'entry_time' => isset($param['entry_time']) ? strtotime($param['entry_time']) : $user->getAttr('entry_time'),
            ];
            
            // 如果提供了新密码，则更新密码，使用password字段触发模型中的哈希修改器
            if (!empty($param['reg_pwd'])) {
                $data['password'] = $param['reg_pwd'];
            }
            
            // 更新用户信息
            $result = $this->userModel->updateUserInfo($param['id'], $data);
            
            if ($result) {
                return $this->success('保存成功');
            } else {
                return $this->error('保存失败', 500);
            }
        } catch (\Exception $e) {
            return $this->error('保存失败', 500);
        }
    }
    
    /**
     * 设置用户状态
     */
    public function set()
    {
        $param = Request::param();
        
        if (empty($param['id'])) {
            return $this->error('参数错误', 400);
        }
        
        if (!isset($param['status'])) {
            return $this->error('状态参数不能为空', 400);
        }
        
        try {
            // 检查用户是否存在
            $user = $this->userModel->getInfoById($param['id']);
            
            if (!$user) {
                return $this->error('用户不存在', 404);
            }
            
            // 更新用户状态
            $result = $this->userModel->updateUserInfo($param['id'], [
                'status' => $param['status'],
            ]);
            
            if ($result) {
                $statusText = $param['status'] == 1 ? '启用' : '禁用';
                return $this->success($statusText . '成功');
            } else {
                return $this->error('操作失败', 500);
            }
        } catch (\Exception $e) {
            return $this->error('操作失败', 500);
        }
    }
    
    /**
     * 删除用户
     */
    public function del()
    {
        $param = Request::param();
        
        if (empty($param['id'])) {
            return $this->error('参数错误', 400);
        }
        
        try {
            // 检查用户是否存在
            $user = $this->userModel->getInfoById($param['id']);
            
            if (!$user) {
                return $this->error('用户不存在', 404);
            }
            
            // 删除用户
            $result = $this->userModel->deleteUser($param['id']);
            
            if ($result) {
                return $this->success('删除成功');
            } else {
                return $this->error('删除失败', 500);
            }
        } catch (\Exception $e) {
            return $this->error('删除失败', 500);
        }
    }
    
    /**
     * 重置密码
     */
    public function resetPassword()
    {
        $param = Request::param();
        
        if (empty($param['id'])) {
            return $this->error('参数错误', 400);
        }
        
        try {
            // 检查用户是否存在
            $user = $this->userModel->getInfoById($param['id']);
            
            if (!$user) {
                return $this->error('用户不存在', 404);
            }
            
            // 重置密码为123456，使用password字段触发模型中的哈希修改器
            // 注意：updateUserInfo方法会自动处理reg_pwd字段
            $result = $this->userModel->updateUserInfo($param['id'], [
                'password' => '123456',
            ]);
            
            if ($result) {
                return $this->success('密码重置成功');
            } else {
                return $this->error('重置失败', 500);
            }
        } catch (\Exception $e) {
            return $this->error('重置失败', 500);
        }
    }
    
    /**
     * 用户列表
     */
    public function list()
    {
        $param = Request::param();
        $page = $param['page'] ?? 1;
        $limit = $param['limit'] ?? 15;
        
        try {
            $where = [];
            
            // 搜索条件 - 同时支持keyword和keywords参数，搜索姓名、用户名和手机号
            $searchKeyword = $param['keyword'] ?? $param['keywords'] ?? '';
            
            if (!empty($searchKeyword)) {
                $keyword = '%' . trim($searchKeyword) . '%';
                $where[] = [
                    'OR',
                    ['name', 'like', $keyword],
                    ['username', 'like', $keyword],
                    ['mobile', 'like', $keyword]
                ];
            }
            
            if (isset($param['status']) && $param['status'] !== '') {
                $where[] = ['status', '=', intval($param['status'])];
            }
            
            if (!empty($param['did'])) {
                $where[] = ['did', '=', intval($param['did'])];
            }
            
            // 查询总数
            $total = $this->userModel->where($where)->count();
            
            // 查询列表
            $list = $this->userModel
                ->where($where)
                ->order('id', 'desc')
                ->page($page, $limit)
                ->select()
                ->toArray();
            
            // 处理数据
            foreach ($list as &$item) {
                $item['department'] = '';
                if (!empty($item['did']) && $item['did'] > 0) {
                    $department = $this->departmentModel
                        ->where('id', $item['did'])
                        ->value('title');
                    $item['department'] = $department ?: '';
                }
            }
            
            return $this->success([
                'list' => $list,
                'total' => $total,
                'page' => $page,
                'limit' => $limit
            ], 'success');
        } catch (\Exception $e) {
            return $this->success([
                'list' => [],
                'total' => 0,
                'page' => $page,
                'limit' => $limit
            ], 'success');
        }
    }
    
    /**
     * 获取部门用户树
     */
    public function getDepartmentUserTree()
    {
        try {
            $tree = $this->departmentModel->getDepartmentUserTree();
            return $this->success($tree, 'success');
        } catch (\Exception $e) {
            return $this->success([], 'success');
        }
    }
    
    /**
     * 获取管理员列表（用于下拉选择）
     */
    public function getAdminList()
    {
        try {
            // 获取管理员用户列表（状态为启用的用户）
            $adminList = $this->userModel
                ->where('status', 1)
                ->field('id, name, username, mobile, email, did, position_id')
                ->order('id', 'asc')
                ->select()
                ->toArray();
                
            // 处理部门和职位信息
            foreach ($adminList as &$user) {
                // 获取部门名称
                if (!empty($user['did'])) {
                    $department = $this->departmentModel
                        ->where('id', $user['did'])
                        ->where('status', '>', 0)
                        ->value('title');
                    $user['dept_name'] = $department ?: '';
                } else {
                    $user['dept_name'] = '';
                }
                
                // 获取职位名称
                if (!empty($user['position_id'])) {
                    $position = $this->positionModel
                        ->where('id', $user['position_id'])
                        ->where('status', '>', 0)
                        ->value('title');
                    $user['position_name'] = $position ?: '';
                } else {
                    $user['position_name'] = '';
                }
                
                // 确保必要的字段存在
                $user['department'] = $user['dept_name'];
                $user['position'] = $user['position_name'];
            }
            
            return $this->success($adminList, '获取管理员列表成功');
        } catch (\Exception $e) {
            return $this->error('获取管理员列表失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 将调试信息写入临时文件
     * @param string $content 要写入的内容
     * @return string 文件路径
     */
    private function writeDebugLog($content) {
        // 确保runtime/debug目录存在
        $debugDir = app()->getRootPath() . 'runtime/debug';
        if (!is_dir($debugDir)) {
            mkdir($debugDir, 0755, true);
        }
        
        // 生成唯一的文件名（基于时间戳和随机数）
        $filename = $debugDir . '/search_debug_' . date('Ymd_His') . '_' . uniqid() . '.log';
        
        // 写入内容到文件
        file_put_contents($filename, $content);
        
        return $filename;
    }
    
    /**
     * 测试搜索功能 - 将调试信息写入文件
     */
    public function testSearch()
    {
        $param = Request::param();
        
        try {
            $where = [];
            
            // 搜索条件 - 同时支持keyword和keywords参数
            $searchKeyword = $param['keyword'] ?? $param['keywords'] ?? '';
            
            if (!empty($searchKeyword)) {
                $keyword = '%' . trim($searchKeyword) . '%';
                $where[] = [
                    'OR',
                    ['name', 'like', $keyword],
                    ['username', 'like', $keyword],
                    ['mobile', 'like', $keyword]
                ];
            }
            
            if (isset($param['status']) && $param['status'] !== '') {
                $where[] = ['status', '=', intval($param['status'])];
            }
            
            if (!empty($param['did'])) {
                $where[] = ['did', '=', intval($param['did'])];
            }
            
            // 执行查询并获取结果
            $list = $this->userModel
                ->where($where)
                ->order('id', 'desc')
                ->select()
                ->toArray();
            
        } catch (\Exception $e) {
            // 记录错误日志
            \think\facade\Log::error('测试搜索功能异常: ' . $e->getMessage());
        }
        
        // 返回成功响应
        return $this->success('测试完成');
    }
    
    /**
     * 修改用户密码
     */
    public function changePassword()
    {
        $param = Request::param();
        
        // 获取当前登录用户ID
        $userId = $this->getUserId();
        
        // 验证参数
        if (empty($param['old_password'])) {
            return $this->error('旧密码不能为空', 400);
        }
        
        if (empty($param['new_password'])) {
            return $this->error('新密码不能为空', 400);
        }
        
        if (strlen($param['new_password']) < 6) {
            return $this->error('新密码长度不能少于6位', 400);
        }
        
        try {
            // 获取用户信息
            $user = $this->userModel->getInfoById($userId);
            
            if (!$user) {
                return $this->error('用户不存在', 404);
            }
            
            // 验证旧密码
            if (!$user->verifyPassword($param['old_password'])) {
                return $this->error('旧密码错误', 400);
            }
            
            // 更新密码，使用password字段触发模型中的哈希修改器
            $result = $this->userModel->updateUserInfo($userId, [
                'password' => $param['new_password'],
            ]);
            
            if ($result) {
                // 密码修改成功后，清空reg_pwd字段
                $this->userModel->updateUserInfo($userId, [
                    'reg_pwd' => '',
                ]);
                return $this->success('密码修改成功');
            } else {
                return $this->error('密码修改失败', 500);
            }
        } catch (\Exception $e) {
            return $this->error('密码修改失败: ' . $e->getMessage(), 500);
        }
    }
    
    /**
     * 获取用户选项（用于下拉选择）
     * @return think\Response
     */
    public function getUserOptions()
    {
        try {
            // 获取所有启用状态的用户
            $users = $this->userModel->where('status', 1)->select();
            $options = [];
            foreach ($users as $user) {
                $options[] = [
                    'id' => $user->id,
                    'name' => $user->name
                ];
            }
            return $this->success($options, '获取成功');
        } catch (\Exception $e) {
            // 记录错误日志
            $this->writeDebugLog($e->getMessage());
            return $this->error('获取失败');
        }
    }
}